package com.zch.starter.opentelemetry.code.mode.springboot.starter.config;

import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

public class LoggingSpanExporterWrapper implements SpanExporter {
    private static final Logger logger = LoggerFactory.getLogger("OTLP-EXPORTER");
    private final SpanExporter delegate;
    private String endpoint;

    public LoggingSpanExporterWrapper(SpanExporter delegate,String endpoint) {
        this.delegate = delegate;
        this.endpoint = endpoint;
    }

    @Override
    public CompletableResultCode export(Collection<SpanData> spans) {
        // 记录导出尝试
        logger.info("Exporting {} spans to {}", spans.size(), getEndpointInfo());

        // 执行实际导出 result 结果异步返回result.whenComplete 可以添加告警之类的
        CompletableResultCode result = delegate.export(spans);

        // 异步监听导出结果
        result.whenComplete(() -> {
            if (result.isSuccess()) {
                logger.debug("Successfully exported {} spans", spans.size());
            } else {
                logger.error("Failed to export {} spans. Endpoint: {}",
                        spans.size(), getEndpointInfo());
            }
        });

        return result;
    }

    @Override
    public CompletableResultCode flush() {
        return delegate.flush();
    }

    @Override
    public CompletableResultCode shutdown() {
        return delegate.shutdown();
    }

    private String getEndpointInfo() {
     return this.endpoint;
    }
}
